﻿using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using Abp.ObjectMapping;
using Microsoft.EntityFrameworkCore;
using yoyosoft.BookList.BookListManagement.Book;
using yoyosoft.BookList.BookManagement.Books.Dto;

namespace yoyosoft.BookList.BookManagement.Books
{
    public class BookAppService : BookListAppServiceBase,IBookAppService
    {
        private readonly IRepository<Book, long> _bookRepository;

        public BookAppService(IRepository<Book, long> bookRepository)
        {
            this._bookRepository = bookRepository;
        }

        public async Task<PagedResultDto<BookListDto>> GetPagdBook(GetBookInput input)
        {
            var query = _bookRepository.GetAll().AsNoTracking()
                .WhereIf(!input.FilterText.IsNullOrWhiteSpace(),u=>u.Name.Contains(input.FilterText));
           var count = await query.CountAsync();
           var entitylist = await query.OrderBy(u=>u.Id).PageBy(input).ToListAsync();
           var entitylistdto = entitylist.MapTo<List<BookListDto>>();
           return new PagedResultDto<BookListDto>(count, entitylistdto);
        }

        public async Task BookCreateOrUpdate(CreateOrUpdateBookInput input)
        {
           var id = Convert.ToInt32(input.Book.Id);
           var entity= await _bookRepository.GetAsync(id);
            if (entity!=null)
            {
               await BookUpdate(input.Book);
            }
            else
            {
               await BookCreate(input.Book);
            }
        }

        public async Task BookCreate(BookEditDto input)
        {
            var entity = input.MapTo<Book>();
            await _bookRepository.InsertAsync(entity);
        }
        public async Task BookUpdate(BookEditDto input)
        {
            Debug.Assert(input.Id!=null, "input.Id!=null");
            //var id = Convert.ToInt32(input.Id);
            //var entity = await _bookRepository.GetAsync(id);
            //if (entity != null)
            //{
                var entity = input.MapTo<Book>();
                await _bookRepository.UpdateAsync(entity);
           // }

        }


        public async Task BookDelete(long id)
        {
          await _bookRepository.DeleteAsync(id);
        }

        public async Task BatchBookDelete(List<long> id)
        {
            await _bookRepository.DeleteAsync(u => id.Contains(u.Id));
        }
    }
}
